﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CCWpf.ViewModels
{
    public class RelayCommand : ICommand
    {
        public event EventHandler? CanExecuteChanged;

        //要执行的操作
        private Action<object> actExecute;
        //是否可以执行
        private Func<object, bool> canExecuteFunc;

        public RelayCommand() { }
        public RelayCommand(Action<object> execute):this(execute,null) 
        {
            
        }
        /// <summary>
        /// 通过要执行的操作和是否可以执行
        /// </summary>
        /// <param name="execute"></param>
        /// <param name="canExecute"></param>
        public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
        { 
            this.actExecute = execute;
            this.canExecuteFunc = canExecute;
        }
        public bool CanExecute(object? parameter)
        {
            if (canExecuteFunc != null)
            {
                return canExecuteFunc(parameter);
            }
            else
            {
                return true;
            }
        }

        public void Execute(object? parameter)
        {
           if (actExecute == null)
                return;

            actExecute(parameter);
        }
        /// <summary>
        /// 执行CanExecutes事件
        /// </summary>
        public void OnCanExecuteChanged()
        { 
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}
